<template>
  <div class="center_management_wrapper">
    <!-- 💭主要页面 -->
    <div class="main_page">
      <div class="search_part">
        <el-button size="mini" type="primary" @click="handleBatchRelevance()">批量关联</el-button>
      </div>
      <div class="table_part">
        <!-- 表格 -->
        <el-table :data="tableData" :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }" :stripe="true">
          <el-table-column align="center" label="中心编号" prop="coreCode"></el-table-column>
          <el-table-column align="center" label="中心名称" prop="coreName"></el-table-column>
          <!-- 动态列部分 -->
          <el-table-column
            v-for="item in ChangedTableStructure"
            :key="item.dataIndex"
            :label="item.title"
            :prop="item.dataIndex"
            align="center"
          >
            <template v-slot="{ row }">
              <!-- 单选框 -->
              <el-checkbox
                v-model="row[item.dataIndex].checked"
                style="margin-right: 4px"
                :disabled="row[item.dataIndex].checkDisabled"
              ></el-checkbox>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-row type="flex" justify="end" style="margin-top: 24px">
          <el-pagination
            @current-change="handleCurrentChange()"
            :current-page="pageParams.page"
            :page-size="pageParams.pageSize"
            layout="total,prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </el-row>
      </div>
    </div>
    <!-- 💭批量关联弹窗部分 -->
    <el-dialog title="批量关联中心" :visible="relevancyDiaVis" @close="handleRelevancyDiaCancel()" width="600px">
      <el-form ref="relevancyFormRef" :model="relevancyData" label-width="120px" :rules="formRules">
        <el-form-item label="目标版本：" prop="newVersionId">
          <el-select
            @change="handelTargetVersionChange"
            v-model="relevancyData.newVersionId"
            size="mini"
            style="width: 60%"
          >
            <el-option
              v-for="item in targetVersionOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="当前版本：">
          <el-select v-model="relevancyData.oldVersionId" size="mini" style="width: 60%">
            <el-option
              v-for="item in currentVersionOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="中心名称：" prop="coreIds">
          <el-select multiple v-model="relevancyData.coreIds" size="mini" style="width: 60%; margin-right: 8px">
            <el-option
              v-for="item in coreNameOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
          <el-button type="primary" size="mini" @click="handleCoreNameSelectAll">全选(可升级的中心)</el-button>
        </el-form-item>
        <span style="color: red; margin-left: 100px; margin-top: 12px; display: inline-block; font-weight: bold;">提示：中心数据库版本升级后，需重新进入项目后生效。</span>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleRelevancyDiaCancel()" size="mini">取 消</el-button>
        <el-button type="primary" @click="handleRelevancyDiaConfirm()" size="mini" :loading="loading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { cloneDeep } from 'lodash-es'
export default {
  data() {
    return {
      relevancyDiaVis: false,
      pageParams: {
        pageNo: 1,
        pageSize: 10,
      },
      total: null,
      projectId: '',
      projectDatabaseId: '',
      ChangedTableStructure: [],
      tableData: [],
      relevancyData: {
        newVersionId: '',
        coreIds: [],
        oldVersionId: '',
      },
      // 数据1
      dataOne: '',
      // 数据3
      dataThree: '',
      dataThreeOrigin: '',
      // 原始表格数据
      originTableData: [],
      // 目标版本下拉项
      targetVersionOptions: [],
      // 中心名称下拉项
      coreNameOptions: [],
      // 当前版本下拉项
      currentVersionOptions: [],
      formRules: {
        newVersionId: [{ required: true, message: '请填写', trigger: 'blur' }],
        coreIds: [{ required: true, message: '请填写', trigger: 'blur' }],
      },
      loading: false
    }
  },
  created() {
    this.projectId = localStorage.getItem('sys-project-id') || ''
    this.projectDatabaseId = localStorage.getItem('project-database-Id') || ''
    this.handleData()
  },
  methods: {
    ...mapActions('databaseVersionChange', [
      'getDatabaseCRFVersionUpTablAPI',
      'getDatabaseCRFVersionUpCoreListAPI',
      'getFindByTargetVersionCoreAPI',
      'upgradeDatabaseCRFVersionUpAPI',
    ]),
    // 1. 获取表格数据
    async getTableData() {
      const params = {
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
      }
      const res = await this.getDatabaseCRFVersionUpCoreListAPI({ params })
      this.dataOne = res.data.records
      this.total = res.data.total
    },

    // 2. 获取表结构
    async getListStructure() {
      const params = {
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
      }
      const res = await this.getDatabaseCRFVersionUpTablAPI({ params })
      this.dataThreeOrigin = cloneDeep(res.data)
      this.dataThree = res.data.reverse()
    },
    // 数据三个接口的数据处理
    async handleData() {
      this.ChangedTableStructure = []
      await Promise.all([this.getTableData(), this.getListStructure()])
      const totalDataId = []
      this.dataThree.forEach(item => {
        this.ChangedTableStructure.push({
          title: item.useVersion + '(' + item.databaseNum + ')',
          dataIndex: item.id,
        })
        totalDataId.push(item.id)
      })
      this.dataOne.forEach(item => {
        totalDataId.forEach(ite => {
          item[ite] = {
            checked: false,
            checkDisabled: true,
          }
        })
        if (item.databaseVersionId) {
          item.databaseVersionId.forEach(it => {
            item[it].checked = true
          })
        }
      })
      this.tableData = this.dataOne
      this.targetVersionOptions = this.dataThree.map(item => ({
        label: item.useVersion + '(' + item.databaseNum + ')',
        value: item.id,
      }))
      this.targetVersionOptions.reverse()
    },
    // 点击批量关联
    handleBatchRelevance() {
      this.relevancyDiaVis = true
    },
    // 选择目标版本
    async handelTargetVersionChange(val) {
      if (val) {
        const params = {
          projectId: this.projectId,
          projectDatabaseId: this.projectDatabaseId,
          versionId: val,
        }
        const res = await this.getFindByTargetVersionCoreAPI({ params })
        this.coreNameOptions = res.data.map(item => {
          let disabled = false
          if (val === item.versionId) {
            disabled = true
          }
          return {
            label: item.coreName,
            value: item.id,
            disabled: disabled,
          }
        })
        console.log(this.dataThreeOrigin, 'dataThreeOrigin')
        console.log(this.dataThree, 'dataThree')
        const arr = cloneDeep(this.dataThreeOrigin)
        const findIndex = arr.findIndex(item => val === item.id)
        arr.splice(0, findIndex + 1)
        this.currentVersionOptions = arr.map(item => ({
          label: item.useVersion,
          value: item.id,
        }))
      }
    },
    // 中心名称点击全选
    handleCoreNameSelectAll() {
      let length = 0
      this.coreNameOptions.forEach(item => {
        if (!item.disabled) {
          length = length + 1
        }
      })
      if (this.relevancyData.coreIds.length !== length) {
        this.relevancyData.coreIds = []
        this.coreNameOptions.forEach(item => {
          if (!item.disabled) this.relevancyData.coreIds.push(item.value)
        })
      }
    },
    // 页码改变
    handleCurrentChange(val) {
      this.pageParams.pageNo = val
      this.getTableData()
    },
    // 批量关联公共关闭
    publicCloseRelevancyDia() {
      this.$refs.relevancyFormRef.resetFields()
      this.relevancyData.newVersionId = ''
      this.relevancyData.coreIds = []
      this.relevancyData.oldVersionId = ''
      this.relevancyDiaVis = false
    },
    // 批量关联弹窗取消
    handleRelevancyDiaCancel() {
      this.publicCloseRelevancyDia()
    },
    // 批量关联弹窗确认
    async handleRelevancyDiaConfirm() {
      await this.$refs.relevancyFormRef.validate()
      this.loading = true
      const data = {
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
        ...this.relevancyData,
      }
      const res = await this.upgradeDatabaseCRFVersionUpAPI({ data })
      this.loading = false
      if (res.code === 200) {
        this.$message.success('批量关联成功！')
        this.handleData()
        this.publicCloseRelevancyDia()
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.center_management_wrapper {
  background-color: $white;
  height: 100%;
  padding: 12px;
  .main_page {
    .table_part {
      margin-top: 24px;
    }
  }
}
</style>
